package DAO;

import Entidad.UsuariosGerente;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;

public class DAO_UsuariosGerente{

    public String create(UsuariosGerente usuario, EntityManager emc) {
        emc.getTransaction().begin();
        try {
            emc.persist(usuario);
            emc.getTransaction().commit();
            return "Succes";
        } catch (Exception e) {
            System.out.println(e);
            emc.getTransaction().rollback();
            return "Fail";
        }
    }

    public void update(UsuariosGerente viejo, UsuariosGerente nuevo, EntityManager em){
        em.getTransaction().begin();
        try{
            Query q = em.createQuery("UPDATE UsuariosGerente s SET s.username = '" +
                    nuevo.getUsername() + "', s.password = '"+ nuevo.getPassword()  +
                    "' WHERE s.username = '" + viejo.getUsername() + "'");
            q.executeUpdate();
            em.getTransaction().commit();
        }catch(Exception e){
            System.out.println(e);
            em.getTransaction().rollback();
        }
    }
    
    public String delete(String username, EntityManager em){
        em.getTransaction().begin();
        try{
            Query q = em.createQuery("DELETE FROM UsuariosGerente u WHERE u.username = '" + username + "'");
            q.executeUpdate();
            em.getTransaction().commit();
            return "Succes";
        }catch(Exception e){
            System.out.println(e);
            em.getTransaction().rollback();
            return "Fail";
        }
    }

    public UsuariosGerente buscar_usuario(String username, EntityManager em){
        try{
            Query q = em.createQuery("SELECT u FROM UsuariosGerente as u WHERE u.username = '" + username + "'");
            return (UsuariosGerente)q.getSingleResult();
        }catch(Exception e){
            System.out.println(e);
            return null;
        }
    }

    public List<UsuariosGerente> getUsuarios(EntityManager em){
        try{
            Query q = em.createQuery("SELECT u FROM UsuariosGerente as u");
            return q.getResultList();
        }catch(Exception e){
            System.out.println(e);
            return null;
        }
    }
}